<template>
  <view class="income-container">
    
    <!-- 余额统计区域 -->
    <view class="balance-section">
      <view class="balance-item">
        <text class="balance-label">当前现金余额（元）</text>
        <view class="balance-amount-container">
          <text class="balance-amount">{{ formatAmount(currentBalance) }}</text>
          <button class="withdraw-btn" @click="withdraw">提现</button>
        </view>
      </view>
      <view class="stats-item">
        <view class="stat">
          <text class="stat-label">累计收入（元）</text>
          <text class="stat-value">{{ formatAmount(totalIncome) }}</text>
        </view>
        <view class="stat">
          <text class="stat-label">累计提现（元）</text>
          <text class="stat-value">{{ formatAmount(totalWithdraw) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 明细列表 -->
    <view class="detail-section">
      <view class="detail-header">
        <text class="detail-title">收支明细</text>
        <view class="filter">
          <image src="/static/logo.png" class="filter-icon" mode="aspectFit"></image>
          <text class="filter-text">日期</text>
        </view>
      </view>
      
      <scroll-view class="detail-list" scroll-y>
        <view v-if="displayRecords.length === 0" class="empty">
          <text>暂无收支记录</text>
        </view>
        <view 
          v-else
          class="detail-item" 
          v-for="(record, index) in displayRecords" 
          :key="index"
        >
          <view class="detail-content">
            <text class="detail-name">{{ record.name }}</text>
            <text class="detail-time">交易时间：{{ record.time }}</text>
          </view>
          <text :class="['amount', { 'positive': record.isIncome, 'negative': !record.isIncome }]">
            {{ record.isIncome ? '+' : '' }}{{ formatAmount(Math.abs(record.amount)) }}
          </text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import request from '@/utils/request';



// 定义提现记录类型
interface WithdrawRecord {
  id: string | null;
  merchantId: string | null;
  cashWithdrawal: number;
  bankCardNumber: string | null;
  realName: string | null;
  status: string | null;
  createBy: string | null;
  createTime: string | null;
  updateBy: string | null;
  updateTime: string;
  withdrawalRecord: string;
  currentBalance: string | null;
}

// 定义收入记录类型
interface IncomeRecordData {
  id: string | null;
  name: string;
  price: number;
  carId: string | null;
  couponId: string | null;
  createBy: string | null;
  createTime: string | null;
  deleted: string | null;
  evaluate: string | null;
  orderTime: string | null;
  payStatus: string | null;
  payTime: string | null;
  reservationTime: string | null;
  serviceId: string | null;
  serviceTypeId: string | null;
  status: string | null;
  updateBy: string | null;
  updateTime: string;
  verificationCode: string | null;
}

// 定义前端展示用的统一记录类型
interface DisplayRecord {
  name: string;
  time: string;
  amount: number;
  isIncome: boolean;
}

// 响应式数据
const incomeRecords = ref<IncomeRecordData[]>([]);
const withdrawRecords = ref<WithdrawRecord[]>([]);
const displayRecords = ref<DisplayRecord[]>([]);

// 计算属性：累计收入
const totalIncome = computed(() => {
  // 计算所有收入记录中price字段的总和
  return incomeRecords.value.reduce((sum, record) => {
    // 直接使用number类型的值，无需转换为string再解析
    const price = typeof record.price === 'number' ? record.price : parseFloat(record.price as string) || 0;
    return sum + price;
  }, 0);
});

// 计算属性：累计提现
const totalWithdraw = computed(() => {
  // 计算所有提现记录中cashWithdrawal字段的总和
  return withdrawRecords.value.reduce((sum, record) => {
    // 直接使用number类型的值，无需转换为string再解析
    const withdrawal = typeof record.cashWithdrawal === 'number' ? record.cashWithdrawal : parseFloat(record.cashWithdrawal as string) || 0;
    return sum + withdrawal;
  }, 0);
});

// 计算属性：当前余额 = 累计收入 - 累计提现
const currentBalance = computed(() => {
  return totalIncome.value - totalWithdraw.value;
});

// 格式化金额为字符串，保留两位小数
const formatAmount = (amount: number): string => {
  return amount.toFixed(2);
};
// 返回上一页
const goBack = (): void => {
  uni.navigateBack();
};

// 提现功能
const withdraw = (): void => {
  // 跳转到申请提现页面，并传递当前余额和提现记录
  uni.navigateTo({
    url: '/pages/income/applyWithdraw?currentBalance=' + currentBalance.value + 
         '&withdrawRecords=' + encodeURIComponent(JSON.stringify(withdrawRecords.value))
  });
};

// 合并并处理所有记录用于展示
const mergeAndProcessRecords = () => {
  const records: DisplayRecord[] = [];
  
  // 处理收入记录
  incomeRecords.value.forEach(record => {
    // 确保amount是数字类型
    let amount = 0;
    if (typeof record.price === 'number') {
      amount = record.price;
    } else if (record.price) {
      amount = parseFloat(record.price as string) || 0;
    }
    
    records.push({
      name: record.name || '服务收入',
      time: record.updateTime || '',
      amount: amount,
      isIncome: true
    });
  });
  
  // 处理提现记录
  withdrawRecords.value.forEach(record => {
    // 确保amount是数字类型并为负数
    let amount = 0;
    if (typeof record.cashWithdrawal === 'number') {
      amount = -record.cashWithdrawal;
    } else if (record.cashWithdrawal) {
      amount = -parseFloat(record.cashWithdrawal as string) || 0;
    }
    
    records.push({
      name: '提现',
      time: record.withdrawalRecord || record.updateTime || '',
      amount: amount,
      isIncome: false
    });
  });
  
  // 按时间倒序排列
  records.sort((a, b) => {
    if (!a.time) return 1;
    if (!b.time) return -1;
    return b.time.localeCompare(a.time);
  });
  
  displayRecords.value = records;
};

//获取收入记录
const getIncomeRecords = async () => {
  request({
    url: "/wsy/order/paid", // 接口路径（会自动拼接基地址）
    method: "GET", // 请求方式
    data: {
      mId: 2 // 传递商户ID参数
    }
  })
    .then(res => {
      // 接口请求成功（后端返回200状态码）
      console.log("收入记录：", res);
      // 根据截图，接口返回的数据包含在res中，可能是数组形式
      if (Array.isArray(res)) {
        incomeRecords.value = res;
      } else if (Array.isArray(res.data)) {
        incomeRecords.value = res.data;
      } else if (res.code === 0 && Array.isArray(res.result)) {
        // 常见的接口响应格式
        incomeRecords.value = res.result;
      } else {
        console.error("数据格式不符合预期", res);
        incomeRecords.value = [];
      }
      
      // 数据更新后重新合并处理记录
      mergeAndProcessRecords();
    })
    .catch(err => {
      console.error("获取收入记录失败：", err);
      incomeRecords.value = [];
      mergeAndProcessRecords();
    });
};

//获取提现记录
const getWithdrawRecords = async () => {
  request({
    url: "/wsy/withdrawal", // 接口路径（会自动拼接基地址）
    method: "GET", // 请求方式
    data: {
      mId: 2 // 传递商户ID参数
    }
  })
    .then(res => {
      // 接口请求成功（后端返回200状态码）
      console.log("提现记录：", res);
      // 根据截图，接口返回的数据包含在res中，可能是数组形式
      if (Array.isArray(res)) {
        withdrawRecords.value = res;
      } else if (Array.isArray(res.data)) {
        withdrawRecords.value = res.data;
      } else if (res.code === 0 && Array.isArray(res.result)) {
        // 常见的接口响应格式
        withdrawRecords.value = res.result;
      } else {
        console.error("数据格式不符合预期", res);
        withdrawRecords.value = [];
      }
      
      // 数据更新后重新合并处理记录
      mergeAndProcessRecords();
    })
    .catch(err => {
      console.error("获取提现记录失败：", err);
      withdrawRecords.value = [];
      mergeAndProcessRecords();
    });
  };

// 页面加载时获取数据
onMounted(() => {
  // 直接调用接口获取真实数据，不再使用模拟数据
  getIncomeRecords(); // 获取收入记录
  getWithdrawRecords(); // 获取提现记录
});
</script>

<style lang="scss" scoped>
.income-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 头部导航 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120rpx;
  padding: 0 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
  position: relative;
}

.back-btn {
  font-size: 48rpx;
  color: #333333;
}

.page-title {
  font-size: 36rpx;
  color: #333333;
  font-weight: 600;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-right {
  width: 48rpx;
}

/* 余额统计区域 */
.balance-section {
  background-color: #1989fa;
  padding: 30rpx;
  color: white;
}

.balance-item {
  margin-bottom: 30rpx;
}

.balance-label {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 10rpx;
}

/* 余额和提现按钮的容器 */
.balance-amount-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20rpx;
}

.balance-amount {
  font-size: 60rpx;
  font-weight: 600;
  text-align: center;
  margin-bottom: 20rpx;
}

.withdraw-btn {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  color: #1989fa;
  background-color: white;
  border: none;
  border-radius: 30rpx;
  padding: 0;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  border-top: 1rpx solid rgba(255, 255, 255, 0.3);
  padding-top: 30rpx;
}

.stat {
  flex: 1;
}

.stat:last-child {
  text-align: right;
}

.stat-label {
  display: block;
  font-size: 26rpx;
  opacity: 0.8;
  margin-bottom: 10rpx;
}

.stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
}

/* 明细列表区域 */
.detail-section {
  margin-top: 20rpx;
  background-color: white;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.filter {
  display: flex;
  align-items: center;
}

.filter-icon {
  width: 30rpx;
  height: 30rpx;
  margin-right: 8rpx;
}

.filter-text {
  font-size: 26rpx;
  color: #666;
}

.detail-list {
  padding: 0 30rpx;
  min-height: 600rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-content {
  flex: 1;
}

.detail-name {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.detail-time {
  display: block;
  font-size: 26rpx;
  color: #999;
}

.amount {
  font-size: 36rpx;
  font-weight: 600;
  margin-left: 10rpx;
  margin-right: 45rpx;
}

.positive {
  color: #52c41a;
}

.negative {
  color: #ff4d4f;
}
</style>